<template>
  <el-form
    ref="ruleFormRef"
    :model="newFormInline"
    :rules="formRules"
    label-width="120px"
    class="w-full form-container"
  >
    <el-form-item label="触发器名称" prop="name">
      <el-input v-model="newFormInline.name" placeholder="请输入触发器名称" />
    </el-form-item>
    <el-form-item label="主触发类型" prop="mainType">
      <el-select v-model="newFormInline.mainType" placeholder="请选择类型">
        <el-option label="设备状态变化" :value="1" />
        <el-option label="定时触发" :value="2" />
      </el-select>
    </el-form-item>
    <el-form-item label="次触发类型" prop="subType">
      <el-select v-model="newFormInline.subType" placeholder="请选择类型">
        <el-option label="设备状态变化" :value="1" />
        <el-option label="定时触发" :value="2" />
      </el-select>
    </el-form-item>
    <el-form-item label="触发源" prop="source">
      <el-select v-model="newFormInline.source" placeholder="请选择触发源">
        <el-option label="设备" :value="1" />
        <el-option label="用户" :value="2" />
        <el-option label="定时" :value="3" />
        <el-option label="其他" :value="4" />
      </el-select>
    </el-form-item>

    <!-- 关联事件下拉框 -->
    <el-form-item label="关联事件" prop="eventId">
      <el-select v-model="newFormInline.eventId" placeholder="请选择事件">
        <el-option
          v-for="option in eventOptions"
          :key="option.value"
          :label="option.label"
          :value="option.value"
        />
      </el-select>
    </el-form-item>
    <!-- 目标用户列表 -->
    <el-form-item label="目标用户" prop="targets">
      <el-select v-model="newFormInline.targets" placeholder="请选择目标用户">
        <el-option
          v-for="option in userOptions"
          :key="option.value"
          :label="option.label"
          :value="option.label"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="触发器参数" prop="params">
      <div class="param-container">
        <div class="param-header flex justify-between items-center mb-2">
          <div class="param-title font-semibold">参数配置</div>
          <el-button type="primary" size="small" @click="addParam"
            >添加参数</el-button
          >
        </div>
        <div
          v-if="paramsList.length === 0"
          class="text-center text-gray-500 py-4"
        >
          暂无参数，请点击添加参数
        </div>
        <div v-else class="param-list">
          <div
            v-for="(param, index) in paramsList"
            :key="index"
            class="param-item flex items-center gap-2 mb-2"
          >
            <el-input
              v-model="param.key"
              placeholder="参数名"
              class="param-key"
              style="width: 150px"
            />
            <span class="text-gray-500">=</span>
            <el-input
              v-model="param.value"
              placeholder="参数值"
              class="param-value"
              style="flex: 1"
            />
            <el-button type="danger" size="small" @click="removeParam(index)">
              <el-icon><Delete /></el-icon>
            </el-button>
          </div>
        </div>
      </div>
    </el-form-item>
    <el-form-item label="备注" prop="comment">
      <el-input
        v-model="newFormInline.comment"
        type="textarea"
        :maxlength="200"
        show-word-limit
        :rows="4"
        placeholder="请输入备注，最多200字"
      />
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { ref, watch } from "vue";
import { Delete } from "@element-plus/icons-vue";
import { FormProps } from "../componentsUtils/type/triggerTypes";
import { formRules } from "../componentsUtils/rule/triggerRules";
import { ElMessage } from "element-plus";

const props = withDefaults(defineProps<FormProps>(), {
  formInline: () => ({
    id: 0,
    dealerId: 0,
    tenantId: 0,
    name: "",
    eventId: 0,
    mainType: 0,
    subType: 0,
    source: 0,
    params: "",
    targets: 0,
    comment: ""
  }),
  title: "",
  eventOptions: () => [
    {
      label: "无事件",
      value: 0
    }
  ],
  userOptions: () => [
    {
      label: "无用户",
      value: 0
    }
  ]
});

const newFormInline = ref(props.formInline);
const ruleFormRef = ref();
const paramsList = ref<Array<{ key: string; value: string }>>([]);

// 初始化参数列表
function initParamsList() {
  try {
    if (newFormInline.value.params) {
      const params = JSON.parse(newFormInline.value.params);
      if (Array.isArray(params)) {
        paramsList.value = params;
      } else if (typeof params === "object") {
        paramsList.value = Object.entries(params).map(([key, value]) => ({
          key,
          value: String(value)
        }));
      }
    }
  } catch (error) {
    paramsList.value = [];
  }
}

// 添加参数
function addParam() {
  paramsList.value.push({ key: "", value: "" });
}

// 删除参数
function removeParam(index: number) {
  paramsList.value.splice(index, 1);
}

// 监听参数列表变化，同步到newFormInline.params
watch(
  paramsList,
  newValue => {
    const validParams = newValue.filter(param => param.key.trim() !== "");
    newFormInline.value.params = JSON.stringify(validParams);
  },
  { deep: true }
);

// 初始化
initParamsList();

function getRef() {
  return ruleFormRef.value;
}

defineExpose({ getRef });
</script>

<style scoped>
.param-container {
  padding: 10px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.param-header {
  padding-bottom: 8px;
  border-bottom: 1px solid #e4e7ed;
}

.param-list {
  margin-top: 10px;
}

.form-container {
  box-sizing: border-box;
  max-height: 600px; /* 可根据实际需求调整高度值 */
  padding: 15px;
  overflow-y: auto;
}

/* 自定义滚动条样式（可选） */
.form-container::-webkit-scrollbar {
  width: 6px;
}

.form-container::-webkit-scrollbar-thumb {
  background-color: #dcdfe6;
  border-radius: 3px;
}

.form-container::-webkit-scrollbar-track {
  background-color: #f5f7fa;
}
</style>
